package top.cmx.learn.thread;

/**
 * @author cmx
 */
public class CarStock {
    int cars;

    /**
     * 通知生产
     */
    public synchronized void productCar() {
        try {
            if (cars < 20) {
                System.out.println("生产车……" + cars);

                Thread.sleep(100);
                cars++;
                notifyAll();

            } else {
                wait();
            }
        } catch (InterruptedException e) {
            System.out.println(e.getMessage());
        }
    }

    /**
     * 通知消费车
     */
    public synchronized void consumeCar() {
        try {
            if (cars > 0) {
                System.out.println("生产车……" + cars);
                Thread.sleep(100);
                cars--;
                notifyAll();
            } else {
                wait();
            }
        } catch (InterruptedException e) {

        }
    }

    static class CarProducter implements Runnable {
        CarStock carStock;

        public CarProducter(CarStock clkerk) {
            this.carStock = clkerk;
        }

        @Override
        public void run() {
            while (true) {
                carStock.productCar();
            }
        }
    }

    static class CarConsumer implements Runnable {
        CarStock carStock;

        public CarConsumer(CarStock clkerk) {
            this.carStock = clkerk;
        }

        @Override
        public void run() {
            while (true) {
                carStock.consumeCar();
            }
        }
    }

    public static class ProducerAndConsumer {
        public static void main(String[] args) {
            CarStock carStock = new CarStock();
            CarProducter carProducter = new CarProducter(carStock);
            CarConsumer carConsumer = new CarConsumer(carStock);
            Thread thread = new Thread(carProducter);
            Thread thread2 = new Thread(carProducter);
            Thread thread1 = new Thread(carConsumer);
            Thread thread12 = new Thread(carConsumer);
            thread.start();
            thread2.start();
            thread1.start();
            thread12.start();
        }
    }

}
